/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MessageIO;


import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * SocketMessageManager communicates with MessengerServer with sockets and
 * MulticastSockets
 * @author Mark
 */
public class SocketMessageManager extends MessageManager
    {
    private Socket client;//Socket for outgoing data
    private String serverAddress;//MessengerServer address
    private PacketReceiver receiver;//multicast packet receiver
    private boolean connected = false;//connection status
    private ExecutorService exe;//executor for server

    /**
     * Creates a new SocketMessageManager
     * @param address MessengerServer address
     */
    public SocketMessageManager(String address)
        {
        super();
        serverAddress = address;//sets the MessengerServer address
        exe = Executors.newCachedThreadPool();
        }

    /**
     * Connects to server and sends messages to MessageListener
     * @param listen the listener to be sent to
     */
    @Override
    public void connect(MessageListener listen)
        {
        if (connected)//makes sure its connected
            return;
        try//opens socket connection to messengerserver
            {
            client = new Socket(InetAddress.getByName(serverAddress),
                    SocketConstants.SERVER_PORT);
            receiver = new PacketReceiver(listen);//creates a receiver for
            //incoming messages
            exe.execute(receiver);//executes the runnable receiver
            System.out.println("Started Exe");
            connected = true;//connection updated to true
            }
        catch (IOException io)
            {
            io.printStackTrace();
            }
        }

    /**
     * Disconnect from the server and unregister given MessageListener
     * @param listen listen to be unregister
     */
    @Override
    public void disconnect(MessageListener listen, ChatUsername name)
        {
        if (!connected)
            return;
        try
            {
            //notifies server that client is leaving
            String nameSend = name == null? "" : name.toString();
            Runnable disconnecter = new MessageSender(client, "", nameSend.toString()
                    + SocketConstants.DISCONNECT_STRING);
            Future disconnecting = exe.submit(disconnecter);
            disconnecting.get();//waits for disconnect message to send
            receiver.stopListening();//stops listening and closes socket
            client.close();
            }
        catch (ExecutionException ee)
            {
            ee.printStackTrace();
            }
        catch (InterruptedException ie)
            {
            ie.printStackTrace();
            }
        catch (IOException io)
            {
            io.printStackTrace();
            }
        connected = false;//updates connected to false
        }

    /**
     * Send Message to server
     * @param from username who the message is from
     * @param message the body of the message
     */
    @Override
    public void sendMessage(String from, String message)
        {
//        System.out.println(connected + from + " " + message);
        if (!connected)//makes sure you are connected
            return;
        //Makes a MessageSender to send message
        exe.execute(new MessageSender(client, from, message));
        }


    }
